package com.jy.api.wechat.handler;


import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.jy.api.service.WechatMemberService;
import com.jy.api.wechat.builder.TextBuilder;
import com.jy.api.wechat.service.BaseWxService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@Slf4j
public abstract class ScanHandler extends AbstractHandler {


    @Autowired
    WechatMemberService wechatMemberService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {

        this.logger.info("已关注用户扫码 OPENID: " + wxMessage.getFromUser());

        BaseWxService weixinService = (BaseWxService) wxMpService;

        WxMpXmlOutMessage responseResult = null;
        try {
            responseResult = wechatMemberService.handleSpecial(wxMessage, weixinService);

        } catch (Exception e) {
            this.logger.error(e.getMessage(), e);
        }

        if (responseResult != null) {
            return responseResult;
        }
        System.out.println(JSON.toJSONString(wxMessage));
        try {
            String msg = "关注成功！祝你生活愉快！";
            if (wxMessage.getEventKey().contains("referralId")) {
                msg = "感谢关注";
                return null;
            }
            if (wxMessage.getEventKey().contains("orderId")) {
                msg = "登陆成功";
                return null;
            }
            if (wxMessage.getEventKey().contains("couponInstanceId") ||
                    wxMessage.getEventKey().contains("shareId")) {
                msg = "领取成功";
            }
            if (wxMessage.getEventKey().contains("line")){
                msg="";
                return null;
            }
            return new TextBuilder().build("", wxMessage, weixinService);
        } catch (Exception e) {
            this.logger.error("登陆失败：{}", e.getMessage(), e);
            return new TextBuilder().build("登陆失败！", wxMessage, weixinService);
        }

    }

}
